#include "openFSM.h"

#include "stdio.h"

#if USE_FSM_print

#define ZEROPAD     (1 << 0)    /* pad with zero */
#define SIGN        (1 << 1)    /* unsigned/signed long */
#define PLUS        (1 << 2)    /* show plus */
#define SPACE       (1 << 3)    /* space if plus */
#define LEFT        (1 << 4)    /* left justified */
#define SPECIAL     (1 << 5)    /* 0x */
#define LARGE       (1 << 6)    /* use 'ABCDEF' instead of 'abcdef' */

#define _ISDIGIT(c)  ((unsigned)((c) - '0') < 10)

static int divide(unsigned long *n, int base)
{
    int res;

    res = (int)((*n) % base);
    *n = (long)((*n) / base);

    return res;
}

static int skip_atoi(const char **s)
{
    int i = 0;
    while (_ISDIGIT(**s))
        i = i * 10 + *((*s)++) - '0';

    return i;
}

static char *print_number(char * buf, char *end, unsigned long num, int base, int qualifier, int s, int type)
{
    char c = 0, sign = 0;
    char tmp[32] = {0};
    const char *digits = NULL;
    static const char small_digits[] = "0123456789abcdef";
    static const char large_digits[] = "0123456789ABCDEF";
    int i = 0;
    int size = 0;

    size = s;

    digits = (type & LARGE) ? large_digits : small_digits;
    if (type & LEFT)
    {
        type &= ~ZEROPAD;
    }

    c = (type & ZEROPAD) ? '0' : ' ';

    /* get sign */
    sign = 0;
    if (type & SIGN)
    {
        switch (qualifier)
        {
        case 'h':
            if ((int16_t)num < 0)
            {
                sign = '-';
                num = (uint16_t)-num;
            }
            break;
        case 'L':
        case 'l':
            if ((long)num < 0)
            {
                sign = '-';
                num = (unsigned long)-num;
            }
            break;
        case 0:
        default:
            if ((int32_t)num < 0)
            {
                sign = '-';
                num = (uint32_t)-num;
            }
            break;
        }

        if (sign != '-')
        {
            if (type & PLUS)
            {
                sign = '+';
            }
            else if (type & SPACE)
            {
                sign = ' ';
            }
        }
    }

    i = 0;
    if (num == 0)
    {
        tmp[i++] = '0';
    }
    else
    {
        while (num != 0)
            tmp[i++] = digits[divide(&num, base)];
    }

    size -= i;

    if (!(type & (ZEROPAD | LEFT)))
    {
        if ((sign) && (size > 0))
        {
            size--;
        }

        while (size-- > 0)
        {
            if (buf < end)
            {
                *buf = ' ';
            }

            ++ buf;
        }
    }

    if (sign)
    {
        if (buf < end)
        {
            *buf = sign;
        }
        -- size;
        ++ buf;
    }

    /* no align to the left */
    if (!(type & LEFT))
    {
        while (size-- > 0)
        {
            if (buf < end)
            {
                *buf = c;
            }

            ++ buf;
        }
    }

    /* put number in the temporary buffer */
    while (i-- > 0)
    {
        if (buf < end)
        {
            *buf = tmp[i];
        }

        ++ buf;
    }

    while (size-- > 0)
    {
        if (buf < end)
        {
            *buf = ' ';
        }

        ++ buf;
    }

    return buf;
}

static int __vsnprintf(char *buf, uint32_t size, const char *fmt, va_list args)
{
    uint32_t num = 0;

    int i = 0, len = 0;
    char *str = NULL, *end = NULL, c = 0;
    const char *s = NULL;

    uint8_t base = 0;            /* the base of number */
    uint8_t flags = 0;           /* flags to print number */
    uint8_t qualifier = 0;       /* 'h', 'l', or 'L' for integer fields */
    uint8_t field_width = 0;     /* width of output field */

    str = buf;
    end = buf + size;

    /* Make sure end is always >= buf */
    if (end < buf)
    {
        end  = ((char *) - 1);
        size = end - buf;
    }

    for (; *fmt ; ++fmt)
    {
        if (*fmt != '%')
        {
            if (str < end)
            {
                *str = *fmt;
            }

            ++ str;
            continue;
        }

        /* process flags */
        flags = 0;

        while (1)
        {
            /* skips the first '%' also */
            ++ fmt;
            if (*fmt == '-') flags |= LEFT;
            else if (*fmt == '+') flags |= PLUS;
            else if (*fmt == ' ') flags |= SPACE;
            else if (*fmt == '#') flags |= SPECIAL;
            else if (*fmt == '0') flags |= ZEROPAD;
            else break;
        }

        /* get field width */
        field_width = -1;
        if (_ISDIGIT(*fmt))
        {
            field_width = skip_atoi(&fmt);
        }
        else if (*fmt == '*')
        {
            ++ fmt;
            /* it's the next argument */
            field_width = va_arg(args, int);
            if (field_width < 0)
            {
                field_width = -field_width;
                flags |= LEFT;
            }
        }
        qualifier = 0;

        if (*fmt == 'h' || *fmt == 'l')

        {
            qualifier = *fmt;
            ++ fmt;

        }

        /* the default base */
        base = 10;

        switch (*fmt)
        {
        case 'c':
            if (!(flags & LEFT))
            {
                while (--field_width > 0)
                {
                    if (str < end) *str = ' ';
                    ++ str;
                }
            }

            /* get character */
            c = (uint8_t)va_arg(args, int);
            if (str < end)
            {
                *str = c;
            }
            ++ str;

            /* put width */
            while (--field_width > 0)
            {
                if (str < end) *str = ' ';
                ++ str;
            }
            continue;

        case 's':
            s = va_arg(args, char *);
            if (!s)
            {
                s = "(NULL)";
            }

            for (len = 0; (len != field_width) && (s[len] != '\0'); len++);


            if (!(flags & LEFT))
            {
                while (len < field_width--)
                {
                    if (str < end) *str = ' ';
                    ++ str;
                }
            }

            for (i = 0; i < len; ++i)
            {
                if (str < end) *str = *s;
                ++ str;
                ++ s;
            }

            while (len < field_width--)
            {
                if (str < end) *str = ' ';
                ++ str;
            }
            continue;

        case 'p':
            if (field_width == -1)
            {
                field_width = sizeof(void *) << 1;
                flags |= ZEROPAD;
            }

            str = print_number(str, end,
                               (uintptr_t)va_arg(args, void *),
                               16, qualifier, field_width, flags);
            continue;

        case '%':
            if (str < end)
            {
                *str = '%';
            }
            ++ str;
            continue;

        /* integer number formats - set up the flags and "break" */
        case 'b':
            base = 2;
            break;
        case 'o':
            base = 8;
            break;

        case 'X':
            flags |= LARGE;
        case 'x':
            base = 16;
            break;

        case 'd':
        case 'i':
            flags |= SIGN;
        case 'u':
            break;

        default:
            if (str < end)
            {
                *str = '%';
            }
            ++ str;

            if (*fmt)
            {
                if (str < end)
                {
                    *str = *fmt;
                }
                ++ str;
            }
            else
            {
                -- fmt;
            }
            continue;
        }

        if (qualifier == 'l')

        {
            num = va_arg(args, unsigned long);
        }
        else if (qualifier == 'h')
        {
            num = (uint16_t)va_arg(args, int32_t);
            if (flags & SIGN)
            {
                num = (int16_t)num;
            }
        }
        else
        {
            num = (uint32_t)va_arg(args, unsigned long);
        }

        str = print_number(str, end, num, base, qualifier, field_width, flags);

    }

    if (size > 0)
    {
        if (str < end)
        {
            *str = '\0';
        }
        else
        {
            end[-1] = '\0';
        }
    }

    /* the trailing null byte doesn't count towards the total
    * ++str;
    */
    return str - buf;
}

uint32_t FSM_print(const char *fmt, ...)
{
    va_list args;
    uint32_t length = 0;
    static char rt_log_buf[print_BufferSize];

    va_start(args, fmt);

    length = __vsnprintf(rt_log_buf, print_BufferSize, fmt, args);
    if (length > print_BufferSize - 1)
        length = print_BufferSize - 1;

    LOG_Output(rt_log_buf, length);

    printf("%s", rt_log_buf);

    va_end(args);

    return length;
}

#define FSM_Tprint(fmt, ...){                       \
    FSM_print("[T]"fmt"\n", ##VA_ARGS);             \
}
    


#endif /* USE_FSM_print */


void FSM_PrintInfo(struct FSM_state * fsmState)
{
    printf("[FSM_Info]fsmState:%p\n", fsmState);
    printf("[FSM_Info]name:%s\n", fsmState->name);
    printf("[FSM_Info]entryAction:%p\n", fsmState->entryAction);
    printf("[FSM_Info]continuousAction:%p\n", fsmState->continuousAction);
    printf("[FSM_Info]exitAction:%p\n", fsmState->exitAction);
    printf("[FSM_Info]numTransitions:%d\n", fsmState->numTransitions);
    printf("[FSM_Info]first:%d\n", fsmState->first);
    // printf("exitAction:%s", fsmState->exitAction);
}

void FSM_Copy(struct FSM_state * target, struct FSM_state * source)
{
    target->name                = source->name;
    target->data                = source->data;
    target->entryAction         = source->entryAction;
    target->continuousAction    = source->continuousAction;
    target->exitAction          = source->exitAction;
    target->numTransitions      = source->numTransitions;
    target->first               = source->first;
    target->transitions         = source->transitions;
}

/**
 * @brief 检查有限状态机（FSM）状态的跳转条件并返回结果。
 * 
 * 此函数根据当前FSM状态中的跳转条件，调用指定的动作函数并检查其返回值。
 * 根据不同类型的跳转条件（如布尔值或整数），返回是否满足该条件。
 * 
 * @param fsmState 表示当前FSM状态，包含跳转条件及相关动作的方法。
 * 
 * @return uint8_t 如果跳转条件得到满足则返回1，否则返回0。
 * 
 * @note 该函数不会抛出异常。确保传入的fsmState包含有效的跳转条件和动作函数。
 */
static uint8_t JumpConditionCheck(struct transition transition)
{
    switch (transition.JumpCondition)
    {
    case bool_True:
        if (transition.action() == bool_True) {
            return 1;
        }
        return 0;
    
    case bool_False:
        if (transition.action() == bool_False) {
            return 1;
        }
        return 0;
    
    case int_Positive:
        if (transition.action() > 0) {
            return 1;
        }
        return 0;
    
    case int_Zero:
        if (transition.action() == 0) {
            return 1;
        }
        return 0;
    
    case int_Negative:
        if (transition.action() < 0)
        {
            return 1;
        }
        return 0;
    
    }
}

void FSM_Init(struct FSM_state ** fsmState, struct FSM_state * initialState)
{
    // if ( !fsmState )
    //     return;
    printf("fsmState:%p\n", fsmState);
    *fsmState = initialState;
    printf("fsmState:%p\n", fsmState);
    (*fsmState)->first = 0;
        
    // fsmState->name = initialState->name;
    // fsmState->entryAction = initialState->entryAction;
    // fsmState->continuousAction = initialState->continuousAction;
    // fsmState->exitAction = initialState->exitAction;
    // fsmState->numTransitions = initialState->numTransitions;
    // fsmState->first = 0;
    // fsmState->transitions = initialState->transitions;
    
}

/**
 * @brief 运行有限状态机(FSM)的状态转换。
 * 
 * 该函数用于管理状态机的状态转换逻辑。首次进入某个状态时执行其入口动作，
 * 检测状态在正常运行期间的动作，并根据条件进行状态跳转。
 * 
 * @param fsmState 指向当前FSM状态的指针。函数内会更新其指向，确保状态转换生效。
 * 
 * @param data 用于传递给状态动作函数的数据指针。该数据在动作执行时使用。
 * 
 * @note 函数不返回值。函数不抛出异常。
 */
void FSM_Run(struct FSM_state ** fsmState, void * data)
{
    // 状态机首次进入
    if((*fsmState)->first == 0 && (*fsmState)->entryAction != NULL)
    {
        (*fsmState)->entryAction(data);
        (*fsmState)->first = 1;
    }
    
    // 状态机常规状态检测
    if((*fsmState)->continuousAction != NULL)
    {
        (*fsmState)->continuousAction(data);
    }

    struct FSM_state * NewState;

    // 状态机检测跳转条件
    for(uint8_t i = 0; i < (*fsmState)->numTransitions; i++)
    {
        // 检测跳转条件
        if(JumpConditionCheck((*fsmState)->transitions[i]) == 1)
        {
            (*fsmState)->first = 0;
            if((*fsmState)->exitAction != NULL) {
                (*fsmState)->exitAction(data);
            }
            
            NewState = (*fsmState)->transitions->state;

            printf("%s Next to %s\n", (*fsmState)->name, NewState->name);
            FSM_PrintInfo(NewState);

            *fsmState = NewState;

            break;
        }

    }
    printf("\n\n");
}






